<template>
  <div class="edit-student-modal modal">
    <div class="edit-student">
      <div class="modal-header">
        <div class="blank"></div>
        <span class="modal-title title">{{ text + '学生' }}</span>
        <i class="el-icon-close close-icon" @click="close(false)"></i>
      </div>
      <div class="modal-body">
        <div class="row">
          <div class="item">
            <div class="item-name"><span class="required">*</span>学生姓名</div>
            <div class="data">
              <el-input v-model="localStudent.F_name" maxlength="12" placeholder="请输入学生姓名" required></el-input>
            </div>
          </div>
          <div class="item">
            <div class="item-name">性别</div>
            <div class="data">
              <el-select v-model="gender" value-key="id" placeholder="请选择性别">
                <el-option
                  v-for="item in genderList"
                  :key="item.id"
                  :label="item.name"
                  :value="item"
                ></el-option>
              </el-select>
            </div>
          </div>
        </div>
        <div class="row">
          <div class="item">
            <div class="item-name">家长电话</div>
            <div class="data">
              <el-input
                v-model="localStudent.F_phone"
                maxlength="11"
                placeholder="请输入家长电话"
              ></el-input>
            </div>
          </div>
          <div class="item">
            <div class="item-name">学号/考号</div>
            <div class="data">
              <el-input v-model="localStudent.F_no" placeholder="请输入学号/考号" required></el-input>
            </div>
          </div>
        </div>
        <div class="row">
          <div class="item class-item">
            <span class="item-name"><span class="required">*</span>所在班级</span>
            <div class="data">
              <span class="class-name">{{ localStudent.F_class_name || '未选择班级' }}</span>
              <div class="add-class-wrapper" v-clickoutside="handleClose">
                <el-button 
                  type="primary" 
                  size="small" 
                  class="add-class-btn" 
                  @click="toggleGradeList"
                  icon="el-icon-plus"
                >选择</el-button>
                <transition name="fade">
                  <ul class="grade-list custom-scrollbar" v-if="showGradeList">
                    <li
                      v-for="item in gradeList"
                      :key="item.id"
                      @click="selectGrade(item)"
                      class="grade-item"
                    >
                      {{ item.name }}
                    </li>
                  </ul>
                </transition>
                <transition name="fade">
                  <ul class="class-list custom-scrollbar" v-if="showClassList">
                    <li
                      v-for="item in classList"
                      :key="item.F_class_id"
                      @click="selectClass(item)"
                      class="class-item"
                    >
                      {{ item.F_class_name }}
                    </li>
                  </ul>
                </transition>
              </div>
            </div>
          </div>
        </div>
        <div class="row">
          <div class="item id-number-item">
            <div class="item-name">学生账号</div>
            <div class="data">
              <el-input v-model="localStudent.F_account" placeholder="请输入学生账号"></el-input>
            </div>
          </div>
        </div>
        <div class="row">
          <div class="item id-number-item">
            <div class="item-name">身份证号</div>
            <div class="data">
              <el-input v-model="localStudent.identityNumber" placeholder="请输入身份证号"></el-input>
            </div>
          </div>
        </div>
        <div class="row" v-if="showChooseSubject">
          <div class="item sources-item">
            <div class="item-name">选考科目</div>

            <div class="data">
              <span class="checked-subject">{{ checkedSubjectName || '未选择科目' }}</span>
              <div class="select-courses-wrapper" v-clickoutside="closeCourses">
                <el-button 
                  type="primary" 
                  size="small" 
                  class="add-courses-btn" 
                  @click="toggleCourses"
                  icon="el-icon-plus"
                >选择</el-button>
                <transition name="slide-fade">
                  <div class="course-wrapper" v-show="showCourses">
                    <div class="line">
                      <div class="name">必选科目</div>
                      <el-checkbox disabled checked>语文</el-checkbox>
                      <el-checkbox disabled checked>数学</el-checkbox>
                    </div>
                    <div class="line">
                      <div class="name">外语科目</div>
                      <el-radio-group v-model="language">
                        <el-radio
                          v-for="item in fullLanguage"
                          :key="item.id"
                          :label="item.id"
                          >{{ item.name }}</el-radio
                        >
                      </el-radio-group>
                    </div>
                    <div class="line">
                      <div class="name">选考科目</div>
                      <el-radio-group v-model="courseType">
                        <el-radio
                          v-for="item in $maps.examSubject.courseType"
                          :key="item.id"
                          :label="item.id"
                          >{{ item.name }}</el-radio
                        >
                      </el-radio-group>
                    </div>
                    <div class="line">
                      <div class="name">
                        <p>选考科目</p>
                        <p>(多选2)</p>
                      </div>
                      <el-checkbox-group v-model="checkedSubject">
                        <el-checkbox
                          v-for="item in fullCourses"
                          :key="item.id"
                          :label="item.id"
                          >{{ item.name }}</el-checkbox
                        >
                      </el-checkbox-group>
                    </div>
                  </div>
                </transition>
              </div>
            </div>
          </div>
        </div>
        <div class="row" v-if="type === $maps.type.EDIT">
          <div class="item id-number-item">
            <div class="item-name">密码</div>
            <div class="data">
              <el-input
                v-model="password"
                :disabled="pwdInputDisabled"
                maxlength="10"
                placeholder="密码"
              ></el-input>
              <el-button 
                type="warning" 
                size="small" 
                class="edit-pwd-btn" 
                v-if="pwdInputDisabled"
                @click="resetPassword"
                icon="el-icon-refresh"
              >重置</el-button>
            </div>
          </div>
        </div>
        <el-divider content-position="right">高级操作</el-divider>
        <div class="combine-student-section">
          <el-button 
            type="text" 
            icon="el-icon-share" 
            class="combination-student-btn" 
            @click="showCombineStudent = true"
          >
            合并学生
          </el-button>
        </div>
      </div>
      <div class="modal-footer">
        <div class="btn-group">
          <el-button @click="close(false)" class="cancel-btn">取消</el-button>
          <el-button type="primary" @click="close(true)" class="confirm-btn">确认</el-button>
        </div>
      </div>
    </div>
    <CombineStudent
      v-if="showCombineStudent"
      @closeCombineStudent="closeCombineStudent"
      :student="student"
      :gradeAndClass="gradeAndClass"
    />
  </div>
</template>

<script>
import CombineStudent from './CombineStudent.vue';

import Clickoutside from '@/utils/clickoutside';
import { mapState, mapGetters } from 'vuex';
export default {
  name: 'editStudent',
  components: {
    CombineStudent,
  },
  directives: { Clickoutside },
  props: {
    student: {
      type: Object,
      required: true,
    },
    type: {
      type: Number,
    },
  },
  data() {
    return {
      localStudent: {
        F_name: '',
        F_gender: 0,
        F_phone: '',
        F_no: '', // 学号就是考号
        F_grade: '1', // 该学生所在年级
        F_class_id: '', // 所在班级id
        F_class_name: '',
        F_account: '', // 学生账号
        courseList: [], // 选课的科目id数组json化(一定是6科)
      },
      password: '******',
      pwdInputDisabled: true,

      language: 0,
      courseType: 0, // 默认不选科
      checkedSubject: [],

      gradeAndClass: null,
      genderList: [
        { id: 0, name: '-' },
        { id: 1, name: '男' },
        { id: 2, name: '女' }
      ],
      gender: {},
      grade: {},
      showGradeList: false,
      showClassList: false,
      classList: [],
      showCourses: false,
      text: '编辑',

      showCombineStudent: false,
    };
  },
  computed: {
    ...mapState('school', ['schoolOptions']),
    ...mapGetters('school', [
      'schoolId',
      'schoolSubjectList',
      'schoolSubjectCustomSelect',
      'schoolSubjectCustomForeignSelect',
    ]),
    showChooseSubject() {
      return this.localStudent.F_grade >= 10;
    },
    checkedSubjectName() {
      const list = [this.language, this.courseType, ...this.checkedSubject].filter(e => e !== 0);

      if (!list.length) return;
      else {
        const nameList = this.schoolSubjectList
          .filter((e) => list.includes(e.id))
          .map((e) => e.name);
        return ['语文', '数学', ...nameList].join('、');
      }
    },
    gradeList() {
      const list = [];
      for (let i in this.gradeAndClass) {
        const res = this.$maps.gradeList.find((e) => e.id === Number(i));
        list.push(res);
      }
      return list;
    },
    fullLanguage() {
      return [
        ...this.$maps.examSubject.language,
        ...this.schoolSubjectCustomForeignSelect,
      ];
    },
    fullCourses() {
      return [
        ...this.$maps.examSubject.courses,
        ...this.schoolSubjectCustomSelect,
      ];
    },
  },
  watch: {
    gender() {
      this.localStudent.F_gender = this.gender.id;
    },
    showCourses(val) {
      console.log('选考科目弹窗状态:', val);
      // 确保弹窗可以正常显示
      if (val) {
        // 强制下一帧更新DOM
        this.$nextTick(() => {
          // 如果需要，可以在这里添加其他逻辑
        });
      }
    }
  },
  mounted() {
    this.gradeAndClass = JSON.parse(
      JSON.stringify(this.schoolOptions.F_grades)
    );
    this.text = this.type === this.$maps.type.EDIT ? '编辑' : '添加';
    this.genderList = this.genderList;
    this.localStudent = JSON.parse(JSON.stringify(this.student));
    // 同教师编辑一致：编辑时显示明文密码（如果后端返回），否则补拉详情
    if (this.type === this.$maps.type.EDIT) {
      if (this.localStudent && this.localStudent.F_password) {
        this.password = this.localStudent.F_password;
      } else {
        this.fetchStudentPassword();
      }
    }
    this.gender = this.genderList.find(
      (e) => e.id === this.localStudent.F_gender
    ) || this.genderList[0];

    // 初始化选考科目数据
    if (this.localStudent.courseList && Array.isArray(this.localStudent.courseList)) {
      this.localStudent.courseList.forEach((e) => {
        if (this.fullLanguage.map((u) => u.id).includes(e)) {
          this.language = e;
        }
        if (this.$maps.examSubject.courseType.map((u) => u.id).includes(e)) {
          this.courseType = e;
        }
        if (this.fullCourses.map((u) => u.id).includes(e)) {
          this.checkedSubject.push(e);
        }
      });
    } else {
      console.warn('未找到学生选考科目数据或格式不正确');
    }
  },
  methods: {
    async fetchStudentPassword() {
      try {
        if (!this.localStudent || !this.localStudent.F_id) return;
        const { F_student } = await this.$api.getAStudent({
          F_school_id: this.schoolId,
          F_student_id: this.localStudent.F_id,
        });
        const pwd = (F_student && (F_student.F_password || F_student.password)) || '';
        // 如果后端返回的是加密串而非明文
        const isHash = /^[a-f0-9]{32,}$/.test(pwd);
        if (pwd && !isHash) {
          // 明文密码可直接展示
          this.password = pwd;
        } else if (F_student && F_student.is_default_passwd === true) {
          // 默认密码场景，按系统约定展示默认值
          this.password = '123456';
        }
      } catch (e) {
        console.error('获取学生密码失败:', e);
      }
    },
    resetPassword() {
      this.password = '123456';
      this.pwdInputDisabled = false;
    },
    toggleCourses() {
      this.showCourses = !this.showCourses;
    },
    closeCourses() {
      this.showCourses = false;
      
    },
    close(sign) {
      if (!sign) {
        this.$emit('update');
      } else {
        // 添加必选项验证
        // 去除输入两端的空格
        this.localStudent.F_name = this.localStudent.F_name.trim();
        this.localStudent.F_no = this.localStudent.F_no.trim();
        
        if (!this.localStudent.F_name) {
          this.$message.error('学生姓名不能为空');
          return;
        }
        
        // if (!this.localStudent.F_no) {
        //   this.$message.error('学号/考号不能为空');
        //   return;
        // }
        
        // 验证考号格式（可选，根据实际需求调整）
        // if (this.localStudent.F_no.length < 2) {
        //   this.$message.error('学号/考号长度不能少于2位');
        //   return;
        // }
        
        if (!this.localStudent.F_class_id || !this.localStudent.F_class_name) {
          this.$message.error('请选择所在班级');
          return;
        }

        // 准备需要提交的学生数据
        // 确保选考科目数据被正确保存
        const idList = [this.language, this.courseType, ...this.checkedSubject].filter(e => e !== 0);
        
        // 更新localStudent的courseList
        this.localStudent.courseList = idList;
        
        if (!this.pwdInputDisabled) {
          this.$emit('update', {
            ...this.localStudent,
            F_password: this.password,
          });
        } else {
          this.$emit('update', this.localStudent);
        }
      }
    },
    changeGender(gender) {
      this.genderName = gender;
      this.showGenderList = false;
    },
    handleClose() {
      this.showGradeList = false;
      this.showClassList = false;
    },
    toggleGradeList() {
      this.showClassList = false;
      this.showGradeList = !this.showGradeList;
    },
    selectGrade(grade) {
      this.grade = grade;
      this.localStudent.F_grade = JSON.stringify(grade.id);
      this.classList = this.gradeAndClass[grade.id];
      this.showGradeList = false;
      this.showClassList = true;
    },
    selectClass(item) {
      this.localStudent.F_class_name = item.F_class_name;
      this.localStudent.F_class_id = item.F_class_id;
      this.showGradeList = false;
      this.showClassList = false;
    },
    closeCombineStudent() {
      this.showCombineStudent = false;
      this.$emit('updateCombination');
    },
  },
};
</script>

<style lang="less" scoped>
.edit-student-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.4);
  z-index: 999;
  display: flex;
  justify-content: center;
  align-items: center;
}

.edit-student {
  width: 650px;
  border-radius: 8px;
  background-color: #fff;
  position: relative;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  max-height: 85vh;
  overflow-y: auto;
  
  .modal-header {
    height: 60px;
    padding: 0 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #ebeef5;
    
    .title {
      font-size: 18px;
      font-weight: 600;
      color: #303133;
    }
    
    .close-icon {
      font-size: 20px;
      color: #909399;
      cursor: pointer;
      transition: color 0.3s;
      
      &:hover {
        color: #409EFF;
      }
    }
  }
  
  .modal-body {
    box-sizing: border-box;
    padding: 30px;
    display: flex;
    flex-direction: column;
    font-size: 14px;
    
    .row {
      width: 100%;
      margin-bottom: 20px;
      display: flex;
      justify-content: space-between;
      
      .item {
        box-sizing: border-box;
        width: 48%;
        display: flex;
        
        .item-name {
          min-width: 100px;
          padding: 0 15px;
          background-color: #f5f7fa;
          display: flex;
          justify-content: flex-start;
          align-items: center;
          border: 1px solid #dcdfe6;
          border-right: none;
          border-radius: 4px 0 0 4px;
          color: #606266;
          
          .required {
            color: #f56c6c;
            margin-right: 4px;
          }
        }
        
        .data {
          position: relative;
          width: 100%;
          display: flex;
          flex-grow: 1;
        }
      }
      
      .class-item,
      .id-number-item,
      .sources-item {
        width: 100%;
      }
      
      .class-item,
      .sources-item {
        .data {
          box-sizing: border-box;
          min-height: 40px;
          border: 1px solid #dcdfe6;
          padding: 0 15px;
          position: relative;
          border-radius: 0 4px 4px 0;
          display: flex;
          align-items: center;
          
          .checked-subject,
          .class-name {
            line-height: 40px;
            margin-right: 90px;
            text-align: left;
            flex: 1;
            overflow: hidden;
            color: #606266;
            
            &.pre-selected {
              color: #67c23a;
              font-weight: bold;
              padding-left: 5px;
              position: relative;
              
              &::before {
                content: '';
                display: inline-block;
                width: 8px;
                height: 8px;
                background-color: #67c23a;
                border-radius: 50%;
                margin-right: 8px;
              }
            }
            
            &.empty-locked {
              color: #409EFF;
              font-weight: bold;
              font-style: italic;
              
              &::after {
                content: '(请选择学生班级)';
                color: #F56C6C;
                margin-left: 5px;
                font-size: 12px;
              }
            }
          }
        }
      }
      
      .class-item {
        user-select: none;
        
        .data {
          .add-class-wrapper {
            position: absolute;
            right: 10px;
            z-index: 10;
            
            .add-class-btn {
              position: relative;
              z-index: 11;
            }
            
            .grade-list,
            .class-list {
              max-height: 200px;
              overflow-y: auto;
              position: absolute;
              top: 40px;
              text-align: left;
              z-index: 996;
              color: #606266;
              background-color: #fff;
              box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
              border-radius: 4px;
              
              li {
                padding: 8px 16px;
                cursor: pointer;
                transition: all 0.3s;
                
                &:hover {
                  background-color: #ecf5ff;
                  color: #409EFF;
                }
              }
            }
            
            .grade-list {
              width: 140px;
              right: 0;
            }
            
            .class-list {
              width: 200px;
              right: 0;
              margin-top: 10px;
            }
          }
        }
      }
      
      .sources-item {
        position: relative;
        
        .select-courses-wrapper {
          position: absolute;
          user-select: none;
          right: 10px;
          z-index: 10;
          
          .add-courses-btn {
            position: relative;
            z-index: 11;
          }
          
          .course-wrapper {
            text-align: start;
            box-sizing: border-box;
            position: absolute;
            width: 500px;
            border-radius: 8px;
            right: 0;
            top: 40px;
            padding: 20px;
            background-color: #fff;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
            z-index: 999;
            
            .line {
              display: flex;
              margin-bottom: 16px;
              align-items: center;
              
              .name {
                min-width: 100px;
                padding-right: 20px;
                flex-shrink: 0;
                color: #606266;
                font-weight: 500;
              }
              
              &:last-child {
                margin-bottom: 0;
              }
            }
          }
        }
      }
    }
  }
  
  .modal-footer {
    display: flex;
    height: 60px;
    justify-content: flex-end;
    align-items: center;
    padding: 10px 20px 20px;
    
    .btn-group {
      display: flex;
      align-items: center;
      
      .cancel-btn {
        margin-right: 10px;
      }
    }
  }
  
  .combine-student-section {
    text-align: right;
    margin-top: 10px;
    
    .combination-student-btn {
      font-size: 14px;
    }
  }
}

// 自定义滚动条
.custom-scrollbar {
  &::-webkit-scrollbar {
    width: 6px;
    height: 6px;
  }
  
  &::-webkit-scrollbar-thumb {
    background: #c0c4cc;
    border-radius: 3px;
  }
  
  &::-webkit-scrollbar-track {
    background: #f5f7fa;
    border-radius: 3px;
  }
}

// 动画效果
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s;
}

.fade-enter,
.fade-leave-to {
  opacity: 0;
}

.slide-fade-enter-active,
.slide-fade-leave-active {
  transition: all 0.3s ease;
}

.slide-fade-enter,
.slide-fade-leave-to {
  transform: translateY(-10px);
  opacity: 0;
}
</style>
